﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db;
using System.Threading;

namespace yq.Log
{
    /// <summary>
    /// 错误日志
    /// </summary>
    public class Record
    {

        /// <summary>
        /// 写入异常
        /// </summary>
        /// <param name="title"></param>
        /// <param name="other"></param>
        /// <param name="logLevel"></param>
        /// <returns></returns>
        public static bool Write(string title, string other, LogLevel logLevel = LogLevel.Default)
        {
            string tableName = "Log_" + DateTime.Now.ToString("yyyy_MM_dd");
            try
            {
                if (Config.IsEnable)
                {
                    WriteSQL(tableName, title, other, logLevel.GetHashCode());
                    return true;
                }
              }
            catch
            {

            }
            return false;
        }


        /// <summary>
        /// 异步写日志
        /// </summary>
        /// <param name="title"></param>
        /// <param name="other"></param>
        /// <param name="logLevel"></param>
        public static void WriteAsyn(string title, string other, LogLevel logLevel = LogLevel.Default)
        {
            Thread td = new Thread(() => { Write(title, other, logLevel); });
            td.Start();
        }


        /// <summary>
        /// 写入错误数据
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="title"></param>
        /// <param name="other"></param>
        /// <param name="cn"></param>
        /// <param name="logLevel"></param>
        /// <returns></returns>
        private static void WriteSQL(string tableName, string title, string other, int logLevel = 0)
        {
            //是否存在表
            if (CreateTableExist(tableName) == false)
            {
                //如果没有创建表
                CreateTable(tableName);
            }

            var cn = new Db.DbHelper(Config.DbConnectionString, Config.DbProviderName);
            string sql = "insert into " + tableName + " values('" + "guid".ExtNewGuid() + "','" + title + "',@time," + logLevel + ",@other)";
            var comm = cn.GetSqlStringCommond(sql);
            cn.AddInParameter(comm, "@time", System.Data.DbType.DateTime, DateTime.Now.ToString("s"));
            cn.AddInParameter(comm, "@other", System.Data.DbType.String, other);
            cn.ExecuteNonQuery(comm);


        }


        /// <summary>
        /// 创建表
        /// </summary>
        /// <param name="tableName"></param>
        private static void CreateTable(string tableName)
        {
            //开启事务
            using (DBTrans ts = new Db.DBTrans(Config.DbConnectionString, Config.DbProviderName))
            {
                DbHelper helper = new DbHelper(ts);
                try
                {
                    const string sqlConst = "(LogId  varchar(36) not null,Title nvarchar(100) not null,LogTime datetime not null,LogLevel int not null,Other text,primary key (LogId));";
                    string sqlCreate = " create table " + tableName + " " + sqlConst;
                    helper.ExecuteNonQuery(helper.GetSqlStringCommond(sqlCreate));
                    helper.Commit();
                }
                catch
                {
                    helper.Rollback();
                    throw;
                }

            }

        }


        /// <summary>
        /// 表是否存在
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        private static bool CreateTableExist(string tableName)
        {
            var cn = new Db.DbHelper(Config.DbConnectionString, Config.DbProviderName);
            const string mssql = "select count(1) from sysobjects  where name='{0}' ";
            const string sqlite = "select count(1) from sqlite_master where name='{0}'";

            string sql = "";
            switch (Config.DbProviderName)
            {
                case "System.Data.SQLite": sql = sqlite; break;
                case "System.Data.SqlClient": sql = mssql; break;
                default: new Exception("该数据库类型还没有对应的方法"); break;
            }

            sql = string.Format(sql, tableName);

            int count = Convert.ToInt32(cn.ExecuteScalar(cn.GetSqlStringCommond(sql)));

            return count != 0;
        }


    }
}
